//
//  UIImage+Extension.swift
//  WB
//
//  Created by 汪鹏 on 2017/1/6.
//  Copyright © 2017年 汪鹏. All rights reserved.
//

import Foundation

extension UIImage {
    
    
    /// 设置圆角图片
    ///
    /// - Parameters:
    ///   - rect: 给定的图片大小
    ///   - backColor: 背景视图
    /// - Returns: 返回圆角图片
    func conerRadius(rect:CGRect, backColor:UIColor = UIColor.white, borderColor:UIColor = UIColor.darkGray, linwidth:CGFloat = 2) -> UIImage? {
        
        // 1. 开启图片上下文
        UIGraphicsBeginImageContextWithOptions(rect.size, true, 0)
        
        // 2. 背景填充
        backColor.setFill()
        
        UIRectFill(rect)
        
        // 2. 实例化一个圆形的路径
        let path = UIBezierPath(ovalIn: rect)
        
        // 3. 进行路径剪切
        path.addClip()
        
        // 4. 绘图
        self.draw(in:rect)
        
        // 5. 绘制内切的圆形
        borderColor.setStroke()
        
        path.lineWidth = linwidth
        
        path.stroke()
        
        // 5. 取得图片
        let result = UIGraphicsGetImageFromCurrentImageContext()
        
        // 6. 关闭上下文
        UIGraphicsEndImageContext()
        
        // 返回结果
        return result
    }
    
    /// 异步下载图片
    class func downLoadImage(url:URL, imageView:UIImageView, backColor:UIColor) {
        
        DispatchQueue.global().async {
            
            let image = UIImage(data: try! Data(contentsOf: url))
            
            DispatchQueue.main.async(execute: {
                
                imageView.backgroundColor = backColor
                
                imageView.image = image?.conerRadius(rect:imageView.bounds , backColor: backColor)
            })
        }
    }
    
}
